package com.appspot.moviesessions.provider;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileSystemPosterCache implements PosterCache {

	private SessionDataSource dataSource;
	private FileFactory fileFactory;

	public FileSystemPosterCache(SessionDataSource dataSource,
			FileFactory fileFactory) {
		this.dataSource = dataSource;
		this.fileFactory = fileFactory;
	}

	@Override
	public String cache(long id, String httpUrl) {

		/* Hack to allow local testing. */
		// if("N/A".equals(httpUrl)){
		// return "";
		// }
		httpUrl = httpUrl.replace("127.0.0.1", "10.0.2.2");
		InputStream posterStream = dataSource.fetch(httpUrl);
		OutputStream fileOutputStream = fileFactory.openForWrite(String.format(
				MovieSession.Movie.POSTER_THUMB_PATH_FORMAT, id));
		byte[] bytes = new byte[256];
		int r = 0;
		try {
			do {

				r = posterStream.read(bytes);

				if (r >= 0) {
					fileOutputStream.write(bytes, 0, r);
				}
			} while (r >= 0);
			fileOutputStream.flush();
		} catch (IOException e) {
			throw new RuntimeException("Failed to cache poster", e);
		} finally {
			try {
				posterStream.close();
			} catch (IOException e) {
				throw new RuntimeException("Failed to cache poster", e);
			}
			try {
				fileOutputStream.close();
			} catch (IOException e) {
				throw new RuntimeException("Failed to cache poster", e);
			}
		}

		return String.format(MovieSession.Movie.POSTER_URI_FORMAT, id);
	}

	@Override
	public File get(long id) {
		return fileFactory.openFile(String.format(
				MovieSession.Movie.POSTER_THUMB_PATH_FORMAT, id));
	}
}
